//
//  FollowViewController.m
//  Hive
//
//  Created by 惠俊贝 on 15/9/3.
//  Copyright (c) 2015年 ZM. All rights reserved.
//

#import "FollowViewController.h"
#import "EqpInfo.h"
#import "MANaviRoute.h"
#import "MANaviAnnotation.h"
#import "CommonUtility.h"

@interface FollowViewController ()  {

    UIButton *mapTypeButton;
    UIButton *showTrafficButton;
    UIButton *followButton;
    UIButton *carOrHumanButton;
    
    CLLocationCoordinate2D userLocate;
    CLLocationCoordinate2D eqpLocate;
    
}
@property (nonatomic) AMapSearchType searchType;
@property (nonatomic, strong) AMapRoute *route;

/* 当前路线方案索引值. */
@property (nonatomic) NSInteger currentCourse;
/* 路线方案个数. */
@property (nonatomic) NSInteger totalCourse;

/* 起始点经纬度. */
@property (nonatomic) CLLocationCoordinate2D startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;

/* 用于显示当前路线方案. */
@property (nonatomic) MANaviRoute * naviRoute;

@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;
@end

@implementation FollowViewController
@synthesize eqpInfo;
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    backButton.hidden = NO;
    self.search = [[AMapSearchAPI alloc] initWithSearchKey:[MAMapServices sharedServices].apiKey Delegate:self];
    
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    mapTypeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    mapTypeButton.frame = CGRectMake(SCREEN_WIDTH-40-10, NAVIGATTION_HEIGHT+STATUS_BAR_HEIGHT+10, 40, 40);
    [mapTypeButton setImage:[UIImage imageNamed:@"nav_more2_normal"] forState:UIControlStateNormal];
    [mapTypeButton addTarget:self action:@selector(mapTypeButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:mapTypeButton];
    
    
    
    showTrafficButton = [UIButton buttonWithType:UIButtonTypeCustom];
    showTrafficButton.frame = CGRectMake(SCREEN_WIDTH-40-10, CGRectGetMaxY(mapTypeButton.frame)+10, 40, 40);
    [showTrafficButton setImage:[UIImage imageNamed:@"nav_map_load_normal"] forState:UIControlStateNormal];
    [showTrafficButton setImage:[UIImage imageNamed:@"nav_map_load_pressed"] forState:UIControlStateSelected];
    [showTrafficButton addTarget:self action:@selector(showTrafficButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:showTrafficButton];
    
    followButton = [UIButton buttonWithType:UIButtonTypeCustom];
    followButton.frame = CGRectMake(SCREEN_WIDTH-40-10,  CGRectGetMaxY(showTrafficButton.frame)+10, 40, 40);
    [followButton setImage:[UIImage imageNamed:@"navigation_normal"] forState:UIControlStateNormal];
    [followButton setImage:[UIImage imageNamed:@"navigation_normal"] forState:UIControlStateSelected];
    [followButton addTarget:self action:@selector(followButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:followButton];
    
    carOrHumanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    carOrHumanButton.frame = CGRectMake(SCREEN_WIDTH-40-10,  CGRectGetMaxY(followButton.frame)+10, 40, 40);
    [carOrHumanButton setImage:[UIImage imageNamed:@"location3_normal"] forState:UIControlStateNormal];
    [carOrHumanButton setImage:[UIImage imageNamed:@"location2_normal"] forState:UIControlStateSelected];
    [carOrHumanButton addTarget:self action:@selector(carOrHunmanButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:carOrHumanButton];
    
    self.startCoordinate        = CLLocationCoordinate2DMake(39.910267, 116.370888);
    self.destinationCoordinate  = CLLocationCoordinate2DMake(39.989872, 116.481956);

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSString *eqpName = eqpInfo.EqpName == nil ? @"":eqpInfo.EqpName;

    eqpLocate = CLLocationCoordinate2DMake(eqpInfo.GDLat, eqpInfo.GDLng);
    
    titleLabel.text = eqpName;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/* 驾车导航搜索. */
- (void)searchNaviDrive
{
    
    self.startCoordinate = userLocate;
    self.destinationCoordinate = eqpLocate;
    
    AMapNavigationSearchRequest *navi = [[AMapNavigationSearchRequest alloc] init];
    navi.searchType       = AMapSearchType_NaviDrive;
    navi.requireExtension = YES;
    
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
                                           longitude:self.startCoordinate.longitude];
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    
    self.searchType = AMapSearchType_NaviDrive;
    [self.search AMapNavigationSearch:navi];
}



#pragma mark - event
- (void)mapTypeButtonPress:(id)sender {
    
    switch (self.mapView.mapType) {
        case MAMapTypeStandard: {
            self.mapView.mapType = MAMapTypeSatellite;
            break;
        }
        case MAMapTypeSatellite: {
            self.mapView.mapType = MAMapTypeStandard;
            break;
        }
        default: {
            break;
        }
    }
}

- (void)carOrHunmanButtonPress:(id)sender {
    carOrHumanButton.selected = !carOrHumanButton.selected;
    if (carOrHumanButton.selected) {
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }
    else {
        [self locateEqpInfo];
    }
}

- (void)followButtonPress:(id)sender {
        [self searchNaviDrive];
}

- (void)showTrafficButtonPress:(id)sender {
    
    self.mapView.showTraffic = !self.mapView.showTraffic;
    [showTrafficButton setSelected:self.mapView.showTraffic];
}


- (void)locateEqpInfo {
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(eqpInfo.GDLat, eqpInfo.GDLng);
    [self.mapView setCenterCoordinate:coordinate animated:YES];
   
    
}

#pragma mark - AMapSearchDelegate

/* 导航搜索回调. */
- (void)onNavigationSearchDone:(AMapNavigationSearchRequest *)request
                      response:(AMapNavigationSearchResponse *)response
{
//    if (self.searchType != request.searchType)
//    {
//        return;
//    }
    
    if (response.route == nil)
    {
        return;
    }
    
    self.route = response.route;
    [self updateTotal];
    self.currentCourse = 0;

    
    [self presentCurrentCourse];
}

#pragma mark - Utility
/* 更新"详情"按钮状态. */

- (void)updateTotal
{
    NSUInteger total = 0;
    
    if (self.route != nil)
    {
        switch (self.searchType)
        {
            case AMapSearchType_NaviDrive   :
            case AMapSearchType_NaviWalking : total = self.route.paths.count;    break;
            case AMapSearchType_NaviBus     : total = self.route.transits.count; break;
            default: total = 0; break;
        }
    }
    
    self.totalCourse = total;
}

/* 展示当前路线方案. */
- (void)presentCurrentCourse
{
    /* 公交导航. */
    if (self.searchType == AMapSearchType_NaviBus)
    {
        self.naviRoute = [MANaviRoute naviRouteForTransit:self.route.transits[self.currentCourse]];
    }
    /* 步行，驾车导航. */
    else
    {
        MANaviAnnotationType type = self.searchType == AMapSearchType_NaviDrive? MANaviAnnotationTypeDrive : MANaviAnnotationTypeWalking;
        self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type];
    }
    
    //    [self.naviRoute setNaviAnnotationVisibility:NO];
    
    [self.naviRoute addToMapView:self.mapView];
    
    /* 缩放地图使其适应polylines的展示. */
    [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines] animated:YES];
}

#pragma mapviews
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (!updatingLocation && self.userLocationAnnotationView != nil)
    {
        [UIView animateWithDuration:0.1 animations:^{
            
            double degree = userLocation.heading.trueHeading;
            self.userLocationAnnotationView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f );
            
        }];
    }
    
    userLocate = userLocation.location.coordinate;
    
}
- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    MAAnnotationView *view = [views firstObject];
    
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
        pre.fillColor = [UIColor colorWithRed:0.9 green:0.1 blue:0.1 alpha:0.3];
        pre.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.9 alpha:1.0];
        pre.image = [UIImage imageNamed:@"userPosition"];
        pre.lineWidth = 3;
        //        pre.lineDashPattern = @[@6, @3];
        
        [self.mapView updateUserLocationRepresentation:pre];
        
        view.calloutOffset = CGPointMake(0, 0);
        view.canShowCallout = NO;
        self.userLocationAnnotationView = view;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
